﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AForge.Video.DirectShow;

namespace Quellenverwaltung.UI.Webcam
{
    class Webcam
    {
        private VideoCaptureDevice capture;

        public Webcam()
        {
            init();
        }

        public Boolean isActive()
        {
            return capture != null;
        }

        private void init()
        {
            // Liste mit Videoquellen ermitteln      
            FilterInfoCollection sources = new FilterInfoCollection(FilterCategory.VideoInputDevice);

            if (sources != null)
            {
                int device = 0;
                if (sources.Count > 0)
                {
                    try
                    {
                        if (sources.Count >= Word.Configuration.getConfiguration().WebcamDeviceNumber)
                        {
                            device = Word.Configuration.getConfiguration().WebcamDeviceNumber;
                        }

                        capture = new VideoCaptureDevice(sources[device].MonikerString);

                        // Höchstmögliche Auflösung ermitteln                  
                        if (capture.VideoCapabilities.Length > 0)
                        {
                            int highestSolution = 0;
                            int highestWidth = 0;

                            for (int i = 0; i < capture.VideoCapabilities.Length; i++)
                            {
                                if (capture.VideoCapabilities[i].FrameSize.Width > highestWidth)
                                {
                                    highestSolution = i;
                                    highestWidth = capture.VideoCapabilities[i].FrameSize.Width;
                                }
                            }

                            capture.DesiredFrameSize = capture.VideoCapabilities[highestSolution].FrameSize;
                        }
                    }

                    catch
                    {
                        // ignore
                    }
                }
            }
        }

        public void AddFrameEventHandler(AForge.Video.NewFrameEventHandler handler)
        {
            if (capture != null && handler != null)
            {
                capture.NewFrame += handler;
            }
        }

        public void Start()
        {
            if (capture != null)
            {
                capture.Start();
            }
        }

        public void Stop()
        {
            if (capture != null && capture.IsRunning) 
            { 
                capture.SignalToStop(); 
                capture = null;
            }
        }

    }
}
